<template>
  <div class="top-middle-cmp" style="height:100%;">
    <div style="height: calc(100% - 387px)">
      <div class="dc-left">
        <div class="dc-text">
          年度完成情况
          <dv-decoration3 style="width: 200px; height: 20px"/>
        </div>
      </div>
      <div style="width: 100%; height: calc(100% - 87px)">
        <div id="middlePlanCharts" style="width: 100%; height: calc(100% + 10px)"></div>
      </div>
    </div>
    <div>
      <div class="dc-left">
        <div class="dc-text">
          在产产品停工情况
          <dv-decoration3 style="width: 200px; height: 20px"/>
        </div>
      </div>
      <div style="width: 100%; height: 300px;">
        <div ref="dvScrollBoard" class="dv-scroll-board">
          <div ref="dvScrollRows" :style="'animation-duration:'+(config.data.length>5?(config.data.length-5):1)*6+'s;'"
               class="rows">
            <div v-for="(row, ri) in config.data"
                 :key="'row'+ri"
                 :style="'background-color: '+(ri%2===0?config.evenRowBGC:config.oddRowBGC)+';'"
                 class="row-item">
              <div v-if="config.index" style="width: 40px;padding: 0 10px;">
                <span :style="'background-color: '+config.headerBGC+';'" class="index">{{ ri + 1 }}</span>
              </div>
              <div v-for="(ceil, ci) in row"
                   :key="'ceil'+ci"
                   class="ceil"
                   style=""
                   v-html="ceil">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount, defineExpose, markRaw, nextTick} from 'vue';
import {listPlanLine, listProblem} from "../../../../apis/mes/borad";
import {formatDate} from "../../../../utils/formatTime";
import * as echarts from 'echarts/core';

import {
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  SingleAxisComponent
} from 'echarts/components';
import {
  BarChart,
  GaugeChart,
  LineChart,
  CustomChart
} from 'echarts/charts';
import {CanvasRenderer} from 'echarts/renderers';

echarts.use([
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  SingleAxisComponent, // 添加单轴组件
  BarChart,
  LineChart,
  CustomChart,
  GaugeChart,
  CanvasRenderer
]);

const props = defineProps({
  year: {
    type: Number,
    required: true
  }
});
// 配置参数
const params = ref({
  startTime: '',
  endTime: ''
});
const option = ref({});
const config = ref({
  data: [],
  index: true,
  rowNum: 5,
  headerBGC: "#5470c6",
  oddRowBGC: "rgba(10,29,50,0.8)",
  evenRowBGC: "rgba(0,44,81,0.8)"
});
const hasCalledApi = ref(false);
const interval = ref(null);
const seriesConfig = ref([]); // 添加 seriesConfig 存储配置
const chartInstance = ref(null);
const allSeriesNames = ref(['年完成', '年未完成', '月计划', '月完成', '全部展示']);
const seriesVisibility = ref({
  '年完成': true,
  '年未完成': true,
  '月计划': true,
  '月完成': true,
  '全部展示': true
});
onMounted(() => {
  onMountedHandler()
});
const onMountedHandler = () => {
  hasCalledApi.value = true;
  let yearVal = props.year;
  const chartDom = document.getElementById("middlePlanCharts");
  if (!chartDom) return;
  if (!chartInstance.value) {
    chartInstance.value = markRaw(echarts.init(chartDom));
  }
  listPlanFinish(yearVal);
  createProblem(yearVal);
  window.addEventListener("resize", handleResize);
  // 设置定时刷新
  interval.value = setInterval(() => {
    listPlanFinish(yearVal);
    createProblem(yearVal);
  }, 1000 * 60 * 10);
};
const handleResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize();
  }
};
const listPlanFinish = (yearVal) => {
  const requestParams = {year: yearVal, ...params.value};
  listPlanLine(requestParams).then((res) => {
    if (!res?.success || !res.obj) return;

    const {series, xaxis} = res.obj;
    const data = [
      series["年完成"] || [],
      [],
      series["月计划"] || [],
      series["月完成"] || []
    ];

    const sumData = [];
    if (series["年完成"] && series["年计划"]) {
      series["年完成"].forEach((item, i) => {
        data[1].push(parseInt(series["年计划"][i]) - parseInt(item));
        sumData.push(0);
      });
    } else {
      series["年计划"]?.forEach(() => {
        data[1].push(0);
        sumData.push(0);
      });
    }

    // 创建系列配置 - 确保年计划不在图例中
    seriesConfig.value = [
      {
        name: "年完成",
        type: "bar",
        stack: "YearData",
        data: data[0],
        label: {
          show: true,
          position: "top",
          distance: 5,
          offset: [0, -35],
          textStyle: {color: "#1bac1b", fontSize: 14, fontWeight: "bold"},
          formatter: (p) => p.data > 0 ? p.data : ""
        },
        itemStyle: {borderRadius: [2, 2, 0, 0]},
        barGap: 0,
        barCategoryGap: "15%",
        barWidth: "18%",
        show: seriesVisibility.value['年完成']
      },
      {
        name: "年未完成",
        type: "bar",
        stack: "YearData",
        data: data[1],
        label: {
          show: true,
          position: "top",
          distance: 5,
          offset: [0, -25],
          textStyle: {color: "#409EFF", fontSize: 14, fontWeight: "bold"},
          formatter: (p) => p.data > 0 ? p.data : ""
        },
        itemStyle: {borderRadius: [0, 0, 2, 2]},
        barWidth: "18%",
        show: seriesVisibility.value['年未完成']
      },
      {
        name: "年计划",
        type: "bar",
        stack: "YearData",
        data: sumData,
        itemStyle: {color: "none"},
        silent: true,
        tooltip: {show: false},
        label: {
          show: true,
          position: "top",
          offset: [0, -50],
          textStyle: {color: "#FF6B6B", fontSize: 14, fontWeight: "bold"},
          formatter: (p) => series["年计划"][p.dataIndex] || ""
        },
        barWidth: 0,
        show: true,
        legendHoverLink: false  // 确保不在图例中显示
      },
      {
        name: "月计划",
        type: "line",
        yAxisIndex: 1,
        symbol: "circle",
        symbolSize: 6,
        data: data[2],
        lineStyle: {width: 2, type: "dashed"},
        itemStyle: {color: "#6ECCAF"},
        label: {
          show: true,
          position: "top",
          distance: 12,
          offset: [0, -15],
          textStyle: {color: "#20e7a7", fontSize: 14, fontWeight: "bold"},
          formatter: (p) => p.data > 0 ? p.data : ""
        },
        show: seriesVisibility.value['月计划']
      },
      {
        name: "月完成",
        type: "line",
        yAxisIndex: 1,
        symbol: "triangle",
        symbolSize: 8,
        data: data[3],
        lineStyle: {width: 2},
        itemStyle: {color: "#F4A261"},
        label: {
          show: true,
          position: "top",
          distance: 12,
          offset: [0, -5],
          textStyle: {color: "#F4A261", fontSize: 14, fontWeight: "bold"},
          formatter: (p) => p.data > 0 ? p.data : ""
        },
        show: seriesVisibility.value['月完成']
      },
      {
        name: "全部展示",
        type: "custom", // 自定义类型，不在图表上实际显示
        renderItem: function () {
          return null;
        }, // 不渲染任何内容
        show: seriesVisibility.value['全部展示'],
        legendHoverLink: true
      }
    ];

    // 主配置
    option.value = {
      color: ["#1bac1b", "#409EFF", "#70ecb4", "#f3be0a", "#0cec3a"],
      tooltip: {
        trigger: "axis",
        axisPointer: {type: "shadow"},
        backgroundColor: "rgba(0,0,0,0.7)",
        borderColor: "#999",
        textStyle: {color: "#fff", fontSize: 14},
        formatter: function (params) {
          let result = params[0].name + "<br/>";
          params.forEach(item => {
            if (item.value > 0) {
              const dotColor = item.color;
              result += `<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:${dotColor}"></span>`;
              result += `${item.seriesName}: <b style="color:${dotColor}">${item.value}</b><br/>`;
            }
          });
          return result;
        }
      },
      grid: {
        left: "2%",
        right: "3%",
        top: "15%",
        bottom: "20%",
        containLabel: true
      },
      legend: {
        bottom: "5%",
        top: null,
        height: "20%",
        itemGap: 10, // 减小间距让图例项显示更紧凑
        itemWidth: 10,
        itemHeight: 8,
        textStyle: {
          color: "#fff",
          fontSize: 12,
          rich: {
            customSpan: {
              fontSize: 16,
              width: 60, // 固定宽度确保显示完整
              overflow: 'truncate'
            }
          }
        },
        formatter: (name) => {
          return `{customSpan|${name}}`; // 使用富文本确保显示完整
        },
        selectedMode: "multiple",
        // 确保只显示这5个图例项
        data: [
          {name: "年完成"},
          {name: "年未完成"},
          {name: "月计划"},
          {name: "月完成"},
          {name: "全部展示"}
        ],
        selected: JSON.parse(JSON.stringify(seriesVisibility.value)),
        type: 'scroll'
      },
      xAxis: {
        type: "category",
        data: xaxis,
        axisLine: {lineStyle: {color: "#fff"}},
        axisTick: {show: false},
        axisLabel: {fontSize: 11, interval: 0}
      },
      yAxis: [
        {
          type: "value",
          name: "年计划",
          position: "left",
          splitLine: {lineStyle: {type: "dashed", color: "rgba(255,255,255,0.1)"}},
          axisLabel: {formatter: "{value}", textStyle: {color: "#fff"}}
        },
        {
          type: "value",
          name: "月完成",
          position: "right",
          splitLine: {show: false},
          axisLabel: {formatter: "{value}", textStyle: {color: "#fff"}}
        }
      ],
      dataZoom: [{type: "inside", start: 0, end: 100}],
      series: seriesConfig,
      animationDuration: 800
    };

    // 设置图表选项
    chartInstance.value.setOption(option.value, true);

    // 修复图例点击事件处理
    chartInstance.value.off('legendselectchanged');
    chartInstance.value.on("legendselectchanged", (params) => {
      // 获取当前点击的图例名称
      const clickedSeriesName = params.name;

      // 如果是"全部展示"选项
      if (clickedSeriesName === "全部展示") {
        // 显示所有系列
        allSeriesNames.value.forEach(name => {
          seriesVisibility.value[name] = true;
        });
        seriesVisibility.value['全部展示'] = true;
      } else {
        // 只显示当前选中的系列
        allSeriesNames.value.forEach(name => {
          seriesVisibility.value[name] = (name === clickedSeriesName);
        });
        seriesVisibility.value['全部展示'] = false;
      }
      const updatedSeries = seriesConfig.value.map(serie => {
        // 年计划始终显示
        if (serie.name === "年计划") {
          return {...serie};
        }
        return {
          ...serie,
          show: seriesVisibility.value[serie.name]
        };
      });
      // 直接更新图表
      chartInstance.value.setOption({
        legend: {
          selected: {...seriesVisibility.value}
        },
        series: updatedSeries
      }, {
        replaceMerge: ['series']
      });
    });
  });
};

const dvScrollRows = ref(null);
const createProblem = (yearVal) => {
  const requestParams = {year: yearVal, ...params.value};
  listProblem(requestParams).then((res) => {
    let infoData = [];
    let data = [];
    if (res.success) {
      data = res.obj;
    }
    data.forEach((s) => {
      let arr = [
        '【' + formatDate(s.inputDate, "yyyy-MM-dd HH:mm:ss") + '】 产品型号：' + s.modelName + '， 名称：' + s.productName + '， 编号：' + s.productCode +
        '。 问题类型：' + s.problemType + "。 责任部门：" + (s.dutyDeptName || '未填') + "， 责任人：" + (s.dutyUserName || '未填')
      ];
      infoData.push(arr);
    });
    config.value.data = infoData;
    nextTick(() => {
      if (dvScrollRows.value && dvScrollRows.value.clientHeight > 300) {
        dvScrollRows.value.style.animationPlayState = "running";
      }
    });
  });
};
onBeforeUnmount(() => {
  if (interval.value) {
    clearInterval(interval.value); // 在Vue实例销毁前，清除时间定时器
  }
  window.removeEventListener("resize", handleResize);
  if (chartInstance.value) {
    chartInstance.value.dispose();
    chartInstance.value = null;
  }
});
defineExpose({
  onMountedHandler
})
</script>

<style lang="scss" scoped>
.top-middle-cmp {
  width: 44% !important;
  height: 100%;
  padding: 0 20px;
  box-sizing: border-box;

  .dc-text {
    display: flex;
    flex-direction: column;
    height: 10%;
    font-size: 20px;
    padding: 20px;
    box-sizing: border-box;
  }

  .dc-left .dc-text {
    align-items: flex-start;
    justify-content: center;
  }
}

.dv-scroll-board {
  position: relative;
  width: 100%;
  height: 100%;
  color: #fff;
  overflow: hidden;

  .rows {
    overflow: hidden;
    animation-delay: 2s;
    animation: 5s move linear infinite normal;
    animation-play-state: paused;

    @keyframes move {
      0% {
        transform: translate(0, 0);
      }
      85% {
        transform: translate(0, calc(-100% + 300px));
      }
      100% {
        transform: translate(0, calc(-100% + 300px));
      }
    }

    .row-item {
      padding: 10px 0;
      display: flex;
      align-items: center;
      font-size: 14px;
      transition: all 0.3s;
    }

    .ceil {
      padding: 0 6px;
      box-sizing: border-box;
      white-space: inherit;
      overflow: inherit;
      text-overflow: inherit;
    }

    .index {
      border-radius: 3px;
      padding: 0px 3px;
      width: 26px;
      display: inline-block;
      text-align: center;
    }
  }
}
</style>
